import React from 'react';
import { Spin } from 'antd';
import { WeaLocaleProvider, WeaTools } from 'ecCom';
import ChartPanel from '../../../public/chartpanel/ChartPanel';
import * as teamPortraitApis from "../../../apis/portrait/teamPortrait"

const getLabel = WeaLocaleProvider.getLabel;

const colorArr = [
    'rgba(184,224,98,1)',
    'rgba(45,183,245,1)',
    'rgba(128,87,243,1)',
    'rgba(241,171,61,1)',
    'rgba(251,138,138,1)',
];

export default class TeamPortraitIndex extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            ...props,
            isloading: false,
            workExperienceLoading: false, // 工作经验数据是否正在加载
            ageDistributionLoading: false, // 年龄分布数据是否正在加载
            educationLevelLoading: false, // 教育水平数据是否正在记载
            dutyDistributionLoading: false, // 职务分布数据是否正在加载
            jobDistributionLoading: false, // 岗位分布数据是否正在加载
            sexLoading: false, // 性别分析数据是否正在加载

            interfacesInfo: {},   // 接口信息

            comprehensiveQualityDatas: {
                slogan: {
                    total: {
                        label: '0',
                        color: '#1589DD',
                    },
                    average: {
                        label: '0',
                        color: '#DB8A2B',
                    },
                    score: {
                        label: '0',
                        color: '#DB8A2B',
                    },
                    passrate: {
                        label: '0',
                        color: '#DB8A2B',
                    },
                },
                workExperience: [],
                ageDistribution: [],
                educationLevel: [],
            },
            personStructureDatas: {
                dutyDistribution: [],
                jobDistribution: [],
                sex: [],
            },
        };
    }

    componentWillMount() {
        // 获取页面展示数据
        this.getPageDatas()
    }

    componentWillReceiveProps(newProps) {
        if (!_.isEqual(this.props, newProps)) {
            this.setState({
                ...this.state,
                ...newProps,
            }, () => {
                this.getPageDatas();
            });
        }
    }

    // 获取综合素质总结性描述信息
    getComprehensiveQualityDesc = () => {
        return new Promise((rs) => {
            const handleRes = (res) => {
                let { data } = res
                if (data) {
                    let slogan = {}
                    slogan.total = {
                        label: data.total,
                        color: '#1589DD',
                    }
                    slogan.average = {
                        label: data.average,
                        color: '#DB8A2B',
                    }
                    slogan.score = {
                        label: data.score,
                        color: '#DB8A2B',
                    }
                    slogan.passrate = {
                        label: data.passrate,
                        color: '#DB8A2B',
                    }
                    this.state.comprehensiveQualityDatas.slogan = slogan
                    this.setState({
                        comprehensiveQualityDatas: { ...this.state.comprehensiveQualityDatas }
                    })
                }
                rs()
            }

            // this.getDataByInterfaceCode("1000").then(res => {
            //     handleRes(res)
            // })

            // 模拟数据
            window.setTimeout(() => {
                let res = {
                    data: {
                        total: 99, // 成员总数
                        average: 27, // 平均年龄
                        score: 22.6, // 综合素质评分
                        passrate: '56.7%', // 超过比例
                    }
                }
                handleRes(res)
            }, 1000)
        })
    }

    // 获取工作经验数据
    getWorkExperienceData = () => {
        return new Promise((rs) => {
            this.setState({
                workExperienceLoading: true
            })

            const handleRes = (res) => {
                this.setState({
                    workExperienceLoading: false
                })
                let { data } = res
                if (data) {
                    let formatedData = []
                    data.forEach((d, i) => {
                        formatedData.push({
                            item: d.item + getLabel('26577', '年'),
                            percent: d.percent,
                            color: colorArr[i % colorArr.length],
                        })
                    })
                    this.state.comprehensiveQualityDatas.workExperience = formatedData
                    this.setState({
                        comprehensiveQualityDatas: { ...this.state.comprehensiveQualityDatas },
                    })
                }
                rs()
            }

            // this.getDataByInterfaceCode("1001").then(res => {
            //     handleRes(res)
            // })

            window.setTimeout(() => {
                let res = {
                    data: [
                        { item: '0.5-1', percent: 0.234 },
                        { item: '2-5', percent: 0.366 },
                        { item: '6-10', percent: 0.156 },
                        { item: '11-20', percent: 0.244 }
                    ]
                }
                handleRes(res)
            }, 1000)
        })
    }

    // 获取年龄分布数据
    getAgeDistributionData = () => {
        return new Promise((rs) => {
            this.setState({
                ageDistributionLoading: true,
            })

            const handleRes = (res) => {
                this.setState({
                    ageDistributionLoading: false
                })
                let { data } = res
                if (data) {
                    let formatedData = []
                    data.forEach((d, i) => {
                        formatedData.push({
                            xd: d.item + getLabel('15864', '岁'),
                            yd: d.percent,
                            color: [colorArr[i % colorArr.length].replace('1)', '.4)'), colorArr[i % colorArr.length]],
                        })
                    })
                    this.state.comprehensiveQualityDatas.ageDistribution = formatedData
                    this.setState({
                        comprehensiveQualityDatas: { ...this.state.comprehensiveQualityDatas }
                    })
                }
                rs()
            }

            // this.getDataByInterfaceCode("1002").then(res => {
            //     handleRes(res)
            // })

            window.setTimeout(() => {
                let res = {
                    data: [
                        { item: '20-30', percent: 0.15 },
                        { item: '30-40', percent: 0.25 },
                        { item: '40-50', percent: 0.40 },
                        { item: '50-60', percent: 0.20 },
                    ]
                }
                handleRes(res)
            }, 1000)
        })
    }

    // 获取教育水平数据
    getEducationLevelData = () => {
        return new Promise((rs) => {
            this.setState({
                educationLevelLoading: true,
            });

            const handleRes = (res) => {
                this.setState({
                    educationLevelLoading: false
                })
                let { data } = res
                if (data) {
                    let formatedData = []
                    data.forEach((d, i) => {
                        formatedData.push({
                            item: d.item,
                            percent: d.percent,
                            color: colorArr[i % colorArr.length],
                        });
                    });
                    this.state.comprehensiveQualityDatas.educationLevel = formatedData
                    this.setState({
                        comprehensiveQualityDatas: { ...this.state.comprehensiveQualityDatas }
                    })
                }
                rs()
            }

            // this.getDataByInterfaceCode("1003").then(res => {
            //     handleRes(res)
            // })

            window.setTimeout(() => {
                let res = {
                    data:  [
                        { item: '本科', percent: 0.325 },
                        { item: '大专', percent: 0.675 },
                    ]
                }
                handleRes(res)
            }, 1000);
        })
    }

    // 获取职务分布数据
    getDutyDistributionData = () => {
        return new Promise((rs) => {
            this.setState({
                dutyDistributionLoading: true,
            });

            const handleRes = (res) => {
                this.setState({
                    dutyDistributionLoading: false
                })

                let { data } = res
                if (data) {
                    let formatedData = []
                    data.forEach((d, i) => {
                        formatedData.push({
                            item: d.item,
                            percent: d.percent,
                            color: colorArr[i % colorArr.length],
                        })
                    })
                    this.state.personStructureDatas.dutyDistribution = formatedData
                    this.setState({
                        personStructureDatas: { ...this.state.personStructureDatas },
                    })
                }
                rs()
            }

            // this.getDataByInterfaceCode("1004").then(res => {
            //     handleRes(res)
            // })

            window.setTimeout(() => {
                let res = {
                    data: [
                        { item: '技术支持', percent: 0.600 },
                        { item: '技术研发', percent: 0.400 },
                    ]
                } 
                handleRes(res)
            }, 1000);
        })
    }

    // 获取岗位分布数据
    getJobDistributionData = () => {
        return new Promise((rs) => {
            this.setState({
                jobDistributionLoading: true,
            });

            const handleRes = (res) => {
                this.setState({
                    jobDistributionLoading: false
                })

                let { data } = res
                if (data) {
                    let formatedData = []
                    data.forEach((d, i) => {
                        formatedData.push({
                            xd: d.item,
                            yd: d.count,
                            color: [colorArr[i % colorArr.length].replace('1)', '.4)'), colorArr[i % colorArr.length]],
                        })
                    })
                    this.state.personStructureDatas.jobDistribution = formatedData
                    this.setState({
                        personStructureDatas: { ...this.state.personStructureDatas },
                    })
                }
                rs()
            }

            // this.getDataByInterfaceCode("1005").then(res => {
            //     handleRes(res)
            // })

            window.setTimeout(() => {
                let data = []
                for (let i = 0; i < 1; i++) {
                    let index = i == 0 ? "" : i
                    data = data.concat([
                        { item: '需求分析师' + index, count: 3 },
                        { item: 'UI设计师' + index, count: 8 },
                        { item: '产品设计经理' + index, count: 15 },
                        { item: '产品咨询经理' + index, count: 9 },
                        { item: '产品经理' + index, count: 26 },
                    ])
                }
                let res = {
                    data
                }
                handleRes(res)
            }, 1000);
        })
    }

    // 获取性别分析数据
    getSexData = () => {
        return new Promise((rs) => {
            this.setState({
                sexLoading: true,
            });

            const handleRes = (res) => {
                this.setState({
                    sexLoading: false
                })

                let { data } = res
                if (data) {
                    let formatedData = []
                    data.forEach((d, i) => {
                        formatedData.push({
                            item: d.item,
                            count: d.count,
                            percent: d.percent,
                            color: i == 0 ? '#2DB7F5' : '#8057F3',
                        })
                    })
                    this.state.personStructureDatas.sex = formatedData
                    this.setState({
                        personStructureDatas: { ...this.state.personStructureDatas }
                    })
                }
                rs()
            }

            // this.getDataByInterfaceCode("1006").then(res => {
            //     handleRes(res)
            // })

            window.setTimeout(() => {
                let res = {
                    data:  [
                        {
                            item: getLabel('417', '男性'),
                            count: 80,
                            percent: 0.8,
                            color: '#2DB7F5',
                        }, {
                            item: getLabel('418', '女性'),
                            count: 20,
                            percent: 0.2,
                            color: '#8057F3',
                        },
                    ]
                }
                handleRes(res)
            }, 1000);
        })
    }

    // 根据接口code获取数据
    getDataByInterfaceCode = (code) => {
        const { subId, deptId, includeSub, interfacesInfo } = this.state
        const interfaceObj = interfacesInfo[code]
        if (interfaceObj && interfaceObj.addr) {
            return WeaTools.callApi(interfaceObj.addr, interfaceObj.method || "GET", {
                subId,
                deptId,
                includeSub: includeSub ? "1" : "0"
            })
        } else {
            return new Promise(rs => rs({}))
        }
    }

    // 获取页面展示所需数据
    getPageDatas = () => {
        const { subId, deptId, includeSub, interfacesInfo } = this.state
        if (!_.isEmpty(subId) || !_.isEmpty(deptId)) {
            new Promise(rs => {
                if (_.isEmpty(interfacesInfo)) {
                    teamPortraitApis.getInterfacesInfo({
                        codes: "1000,1001,1002,1003,1004,1005,1006"
                    }).then(res => {
                        this.setState({
                            interfacesInfo: res.data || {}
                        }, () => rs())
                    })
                } else {
                    rs()
                }
            }).then(v => {
                Promise.all([
                    this.getComprehensiveQualityDesc(),
                    this.getWorkExperienceData(),
                    this.getAgeDistributionData(),
                    this.getEducationLevelData(),
                    this.getDutyDistributionData(),
                    this.getJobDistributionData(),
                    this.getSexData()
                ])
            })
        }
    }

    render() {
        const { isloading, workExperienceLoading, ageDistributionLoading, educationLevelLoading, dutyDistributionLoading, jobDistributionLoading, sexLoading,
            comprehensiveQualityDatas, personStructureDatas } = this.state;
        const educationLevelBottomHeight = Math.max(Math.ceil(comprehensiveQualityDatas.educationLevel.length / 3), 1) * 50;
        const dutyDistributionBottomHeight = Math.max(Math.ceil(personStructureDatas.dutyDistribution.length / 3), 1) * 50;
        return (
            <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@3s4pyu`} spinning={isloading}>
                <div className="wea-workrelate-team-portrait-teamhome">
                    <ChartPanel ecId={`${this && this.props && this.props.ecId || ''}_ChartPanel@cl7jvn`}
                        title={getLabel('522377', '综合素质')}
                        slogan={[
                            getLabel('522437', '团队成员共${total}人，平均年龄${average}岁，人员综合素质评分${score}，超过${passrate}的其他部门'),
                            comprehensiveQualityDatas.slogan,
                        ]}
                        charts={[
                            {
                                type: 'singleline',
                                width: '30%',
                                height: 338,
                                title: getLabel('522383', '工作经验'),
                                data: comprehensiveQualityDatas.workExperience,
                                loading: workExperienceLoading,
                                noborder: true,
                            },
                            {
                                type: 'bar',
                                width: '30%',
                                height: 338,
                                title: getLabel('522384', '年龄分布'),
                                scale: {
                                    yd: {
                                        formatter: val => (val = `${val * 100}%`),
                                    },
                                },
                                data: comprehensiveQualityDatas.ageDistribution,
                                loading: ageDistributionLoading,
                                size: 20,
                            },
                            {
                                type: 'pie',
                                width: '30%',
                                height: 288 + educationLevelBottomHeight,
                                title: getLabel('522385', '教育水平'),
                                guideIcon: 'icon-portal-si-o',
                                data: comprehensiveQualityDatas.educationLevel,
                                loading: educationLevelLoading,
                                bottomHeight: educationLevelBottomHeight,
                            },
                        ]}
                    />

                    <ChartPanel ecId={`${this && this.props && this.props.ecId || ''}_ChartPanel@hl81nj`}
                        style={{ marginTop: '30px' }}
                        title={getLabel('522386', '人才结构')}
                        charts={[
                            {
                                type: 'pie',
                                width: '30%',
                                height: 288 + dutyDistributionBottomHeight,
                                title: getLabel('522387', '职务分布'),
                                data: personStructureDatas.dutyDistribution,
                                loading: dutyDistributionLoading,
                                bottomHeight: dutyDistributionBottomHeight,
                                noborder: true,
                            },
                            {
                                type: 'bar',
                                width: '30%',
                                height: 338,
                                title: getLabel('522388', '岗位分布'),
                                scale: {
                                    yd: {
                                        formatter: val => val + getLabel('500497', '人'),
                                    },
                                },
                                data: personStructureDatas.jobDistribution.length > 8 ? personStructureDatas.jobDistribution.slice(0, 8) : personStructureDatas.jobDistribution,
                                loading: jobDistributionLoading,
                                size: 20,
                                hasmore: personStructureDatas.jobDistribution.length > 8,
                                moreProps: {
                                    table: {
                                        columns: [
                                            {
                                                key: "xd",
                                                dataIndex: "xd",
                                                title: getLabel('20580','岗位名称') 
                                            },
                                            {
                                                key: "yd",
                                                dataIndex: "yd",
                                                title: getLabel('1859','人数')
                                            }
                                        ],
                                        dataSource: personStructureDatas.jobDistribution
                                    }
                                }
                            },
                            {
                                type: 'bubble',
                                width: '30%',
                                height: 338,
                                title: getLabel('522389', '性别分析'),
                                unit: getLabel('500497', '人'),
                                data: personStructureDatas.sex,
                                loading: sexLoading,
                            },
                        ]}
                    />
                </div>
            </Spin>
        );
    }
}
